<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Base extends Model
{
    /**
     * 金额 换算单位 (分)
     */
    const CURRENCY_UNIT_CONVERSION = 100;

    /**
     * 状态: 正常
     */
    const STATUS_NORMAL = 1;

    /**
     * 状态: 禁用
     */
    const STATUS_DISABLE = 2;

    const STATUS_MAP = [
        self::STATUS_NORMAL => '启用',
        self::STATUS_DISABLE => '禁用',
    ];

    protected static $logOnlyDirty = true;

    protected static $logAttributes = ['*'];

    protected $guarded = [];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('orderByIdDesc', function (Builder $builder) {
            $builder->orderByDesc($builder->getModel()->getTable() . '.' . $builder->getModel()->getKeyName());
        });
    }

    /**
     * 允许前端传长度
     * @return int
     */
    public function getPerPage(): int
    {
        $path = (string) app('request')->path();
        $isH5 = false !== strpos($path, 'h5');
        $h5WhiteList = ($path === 'api/h5/clients'); // h5 限制白名单
        $perPage = (int) (app('request')->input('per_page', null) ?: parent::getPerPage());

        return (($perPage > 15) && ($isH5 && !$h5WhiteList)) ? 15 : $perPage;
    }

    /**
     * 操作日志 custom 操作
     * @param ActivityLog $activity
     * @param string $eventName
     */
    public function tapActivity(ActivityLog $activity, string $eventName)
    {
        // TODO IP GEO 地址
        $activity->properties = $activity->properties->put('ip', app('request')->ip());
    }

    /**
     * 为数组 / JSON 序列化准备日期。
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }
}
